// import { useStore } from 'vuex';
import { store } from '@/store';
import router from '@/router';
import { PermissionActionType } from '@/store/modules/permission/types';
import { UserActionTypes } from '@/store/modules/user/types';
import whiteList from '@/config/whiteList';

router.beforeEach(async (to, _, next) => {
  // 已登陆
  if (store.state.user.token) {
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      if (store.state.user.roles.length === 0) {
        try {
          await store.dispatch(UserActionTypes.ACTION_GET_USER_INFO, undefined);
          await store.dispatch(PermissionActionType.ACTION_SET_ROUTES);
          next({ ...to, replace: true });
        } catch (error) {
          console.log(error);
        }
      } else {
        next();
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});
